package com.meizhuang.controller;


import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import com.aliyun.teautil.models.*;
import com.meizhuang.base.BaseController;
import com.meizhuang.config.CacheUtils;
import com.meizhuang.result.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@Api(tags = "短信发送接口")
@RestController
public class SMSController extends BaseController {

    @PostMapping(value = "/send")
    @ApiOperation(value = "短信发送接口 参数手机号", notes = "手机号")
    public JsonResult sendMessage(String phone) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = createClient("LTAI5tPwGkobpzmUtxiYkH3Y", "FyUyaNDSRhC0cf8I0crJzrNLKGBYhn");


        StringBuilder sb=new StringBuilder(4);

        for(int i=0;i<4;i++) {
            char ch=STR.charAt(new Random().nextInt(STR.length()));
            sb.append(ch);
        }

        String code = sb.toString();
        CacheUtils.put(SMS_PREFIX + phone,code);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("猿报价")
                .setTemplateCode("SMS_242555937")
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\""+code+"\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return JsonResult.buildSuccess();
    }


    public  com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
}
